#include "fui.h"

static fui_menu_item_t *curr_menus;
static uint8_t curr_len;

static uint8_t curr_idx = 0;
static uint8_t curr_offset = 0; // For turning pages

static uint8_t msgbox_show_flag;

void fui_init(void)
{
    
}

void fui_draw_menu(void)
{
    LCD_Fill(0, 0, LCD_W, LCD_H, BLACK);
    
    // Each page displays 4 elements
	for(uint8_t i = 0;i < 10;i++)
    {
        // If len < 4
        if((i + curr_offset) >= curr_len)
        {
            break;
        }
        uint16_t bg = BLACK;
        if((i + curr_offset) == curr_idx)
        {
            bg = RED;
            LCD_Fill(0, 20 * i, 240, 20 * i + 20, bg);
        }
        LCD_ShowString(3, 20 * i, (uint8_t*)curr_menus[i + curr_offset].title, WHITE, bg, 20, 0);
    }
}

void fui_load_menu(fui_menu_item_t *menus, uint8_t len)
{
    curr_menus = menus;
    curr_len = len;
    
    curr_idx = 0;
    curr_offset = 0;
    
    // load first menu
    fui_draw_menu();
}

void fui_showmsgbox(char *title, char* msg, char* msg1)
{
    msgbox_show_flag = 1;
    
    LCD_Fill(0, 0, LCD_W, LCD_H, BLACK);
    
    LCD_ShowString(0, 0, (uint8_t*)title, RED, BLACK, 20, 0);
    LCD_ShowString(0, 40, (uint8_t*)msg, WHITE, BLACK, 20, 0);
    if(msg1 != NULL)
    {
        LCD_ShowString(0, 60, (uint8_t*)msg1, WHITE, BLACK, 20, 0);
    }
    LCD_ShowString(15, 90, (uint8_t*)"Press any key exit.", GREEN, BLACK, 20, 0);
}

void fui_closemsgbox(void)
{
    if(msgbox_show_flag == 0)
    {
        return;
    }
    msgbox_show_flag = 0;
    
    fui_draw_menu();
}

// down
void fui_keyevt_down(void)
{
    if(msgbox_show_flag)
    {
        fui_closemsgbox();
        return;
    }
    if(curr_idx == (curr_len - 1))
    {
        curr_idx = 0;
        curr_offset = 0;
        // Redraw
        fui_draw_menu();
        return;
    }
    curr_idx++;
    // Execute page turning logic
    if(curr_idx == (curr_offset + 10))
    {
        curr_offset += 10;
    }
    // Redraw
    fui_draw_menu();
}

// up
void fui_keyevt_up(void)
{
    if(msgbox_show_flag)
    {
        fui_closemsgbox();
        return;
    }
    if(curr_idx == 0)
    {
        curr_idx = curr_len - 1;
        curr_offset = curr_idx / 10 * 10; // Erase a digit
        // Redraw
        fui_draw_menu();
        return;
    }
    curr_idx--;
    // Execute page turning logic
    if(curr_idx == (curr_offset - 1))
    {
        curr_offset -= 10;
    }
    // Redraw
    fui_draw_menu();
}

void fui_keyevt_enter(void)
{
    if(msgbox_show_flag)
    {
        fui_closemsgbox();
        return;
    }
    if(curr_menus[curr_idx].callback != NULL)
    {
        curr_menus[curr_idx].callback(curr_idx);
    }
}